package com.example.micro.consumer.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author CodeFarmer
 */
@RestController
@RequestMapping("/rate/limit")
public class RateLimitController {

    /**
     * 基于资源名称限流
     *
     * @SentinelResource
     * 【value 资源名字（需要与方法名相同）】
     * 【blockHandler 限流阻塞处理器】
     */
    @GetMapping("/by/source/name")
    @SentinelResource(value = "bySourceName", blockHandler = "handlerException")
    public Map<String, Object> bySourceName() {
        Map<String, Object> map = new HashMap<>();
        map.put("msg", "安装资源名限流");
        map.put("code", 200);
        return map;
    }

    /**
     * 触发了限流操作，就调用该方法
     *
     * @param ex
     * @return
     */
    public Map<String, Object> handlerException(BlockException ex) {
        Map<String, Object> map = new HashMap<>();
        map.put("msg", ex);
        map.put("code", 200);
        return map;
    }

}
